package com.canbot.u05.activity.roadGuide

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.InputFilter
import android.text.Spanned
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.base.BaseChooseJopActivity
import com.canbot.u05.activity.base.BaseChoosePicActivity
import com.canbot.u05.activity.base.BaseCustomAudioActivity
import com.canbot.u05.activity.base.BaseVoiceSetActivity
import com.canbot.u05.activity.customvoice.tool.CheckStringUtils.isChineseOrEnglish
import com.canbot.u05.activity.free.MediaInfo
import com.canbot.u05.activity.inflate
import com.canbot.u05.activity.presidemode.eventbus.AudioEvent
import com.canbot.u05.activity.startActivityForResult
import com.canbot.u05.bean.guide.MapVoiceAndEyes
import com.canbot.u05.helper.DialogBuildHelper
import com.canbot.u05.helper.RoadRecyclerDecoration
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.utils.OkHttpUtils
import com.canbot.u05.utils.PathConst
import com.canbot.u05.utils.ToastTools
import kotlinx.android.synthetic.main.dialog_set_hot_word.view.*
import kotlinx.android.synthetic.main.road_guide_settings.*
import kotlinx.android.synthetic.main.road_set_item.view.*
import java.io.File
import java.util.*


/**
 * Created by zmp on 2019/7/5 13:37
 * @author zmp
 * 路径指引界面
 */
class RoadSettingActivity : BaseActivityNoTitle() {

    private val mMapJopSetBean: RoadSetBean by lazy { RoadSetBean(6, R.drawable.road_set_point, getString(R.string.as_map_position), getString(R.string.as_map_positon_hint)) }

    private lateinit var toastTools: ToastTools

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.road_guide_settings)
        toastTools = ToastTools.newInstance(this)
        initView()
    }

    lateinit var mRoadGuideBean: RoadGuideBean
    private lateinit var mListOf: MutableList<RoadSetBean>
    private fun initView() {
        setVoice.playMapVoiceAndEyes()
        mRoadGuideBean = intent.getParcelableExtra(RoadGuideActivity.ROAD_GUIDE_INFO)
                ?: RoadGuideBean()
        mListOf = mutableListOf(
                RoadSetBean(0, R.drawable.road_set_name, getString(R.string.name_place), getString(R.string.name_place_hint)),
                RoadSetBean(1, R.drawable.road_set_hot, getString(R.string.road_name_place_hot), getString(R.string.road_name_place_hot_hint)),
                RoadSetBean(2, R.drawable.road_set_location, getString(R.string.place_positon), getString(R.string.place_position_hint)),
                RoadSetBean(3, R.drawable.road_set_logo, getString(R.string.place_logo), getString(R.string.place_logo_hint)),
                RoadSetBean(4, R.drawable.road_set_guide, getString(R.string.place_guide_pic), getString(R.string.place_answer_pic_hint)),
                RoadSetBean(5, R.drawable.road_set_lead, getString(R.string.guide_open), getString(R.string.guide_open_hint),
                        isSwitchType = if (mRoadGuideBean.openGuide) 1 else 0),
                mMapJopSetBean,
                RoadSetBean(7, R.drawable.road_set_voice_icon, getString(R.string.result_voice), getString(R.string.result_voice_hint))
        )
        if (!mRoadGuideBean.openGuide) {
            mListOf.removeAt(6)
        }
        road_back_btn.setOnClickListener {
            showBackDialog(getString(R.string.task_exit_hint))
        }
        roadSetTextView.setOnClickListener {
            saveRoadGuideData()
        }
        roadGuideRecyclerView.layoutManager = LinearLayoutManager(this)
        roadGuideRecyclerView.adapter = MyAdapter()
        roadGuideRecyclerView.addItemDecoration(RoadRecyclerDecoration(this))
    }

    private fun showBackDialog(content: String) {
        DialogBuildHelper.createDialogTip(this)
                .setContent(content, Gravity.CENTER)
                .setClickListener(object : DialogBuildHelper.ITipClickListener() {
                    override fun sure() {
                        finish()
                    }
                }, true).show()
    }

    private fun saveRoadGuideData() {
        if (mRoadGuideBean.roadName.isNullOrEmpty()) {
            toastTools.showText(getString(R.string.task_cannot_empty))
            return
        }
        if (mRoadGuideBean.voiceContent.isNullOrEmpty() && mRoadGuideBean.openGuide) {
            toastTools.showText(getString(R.string.voice_cannot_empty))
            return
        }

        if (mRoadGuideBean.pointMapName.isNullOrEmpty() && mRoadGuideBean.openGuide) {
            toastTools.showText(getString(R.string.open_guide_please_choose_map))
            return
        }

        if (mRoadGuideBean.voiceType == MediaInfo.AUDIO_TYPE_RECODE && !mRoadGuideBean.voiceContent.isNullOrEmpty()) {
            upVoice2Head(arrayListOf(AudioEvent(MediaInfo.AUDIO_TYPE_RECODE, mRoadGuideBean.voiceContent, mRoadGuideBean.voiceContent)))
            return
        }
        upDataType2Service()
    }

    inner class MyAdapter : RecyclerView.Adapter<MyHolder>() {

        override fun onCreateViewHolder(p0: ViewGroup, p1: Int): MyHolder {
            return MyHolder(p0.inflate(R.layout.road_set_item))
        }

        override fun getItemCount(): Int {
            return mListOf.size
        }

        override fun onBindViewHolder(p0: MyHolder, p1: Int) {
            p0.bindData(mListOf[p1])
        }
    }

    inner class MyHolder(item: View) : RecyclerView.ViewHolder(item) {
        private lateinit var mRoadSetBean: RoadSetBean
        private val roadSetIv = item.roadSetIv
        private val roadSetTitleTv = item.roadSetTitleTv
        private val roadSetContentTv = item.roadSetContentTv
        private val roadSetResultTv = item.roadSetResultTv
        private val roadSetSwitchIv = item.roadSetSwitchIv
        private val roadSetToIv = item.roadSetToIv

        init {
            itemView.setOnClickListener {
                when (mRoadSetBean.type) {
                    0, 2 -> {
                        showNameDialog(mRoadSetBean, adapterPosition)
                    }
                    1 -> {
                        showHotWordDialog(adapterPosition)
                    }
                    3 -> {
                        startActivityForResult<BaseChoosePicActivity>(requestCode = CHOOSE_PIC_LOGO)
                    }
                    4 -> {
                        startActivityForResult<BaseChoosePicActivity>(requestCode = CHOOSE_PIC_GUIDE)
                    }
                    5 -> {
                        mRoadSetBean.isSwitchType = when (mRoadSetBean.isSwitchType) {
                            0 -> {
                                mRoadGuideBean.openGuide = true
                                mListOf.add(6, mMapJopSetBean)
                                roadGuideRecyclerView.adapter?.notifyItemInserted(6)
                                1
                            }
                            else -> {
                                mRoadGuideBean.openGuide = false
                                mListOf.removeAt(6)
                                roadGuideRecyclerView.adapter?.notifyItemRemoved(6)
                                0
                            }
                        }
                        roadGuideRecyclerView.adapter?.notifyItemChanged(5)

                    }
                    6 -> {
                        startActivityForResult<BaseChooseJopActivity>(requestCode = CHOOSE_JOP_POSITION)

                    }
                    7 -> {
                        startActivityForResult<BaseCustomAudioActivity>(requestCode = CHOOSE_CUSTOM_VOICE)

                    }
                }
            }
        }

        fun bindData(p1: RoadSetBean) {
            this.mRoadSetBean = p1
            roadSetIv.setImageResource(p1.roadSetDrawable)
            roadSetTitleTv.text = p1.roadSetTitle
            roadSetContentTv.text = p1.roadSetContent
            when (p1.isSwitchType) {
                0, 1 -> {
                    roadSetSwitchIv.visibility = View.VISIBLE
                    roadSetToIv.visibility = View.GONE
                    roadSetResultTv.visibility = View.GONE
                    roadSetSwitchIv.isSelected = p1.isSwitchType == 1
                }
                else -> {
                    roadSetSwitchIv.visibility = View.GONE
                    roadSetToIv.visibility = View.VISIBLE
                    roadSetResultTv.visibility = View.VISIBLE
                    roadSetResultTv.text = when (p1.type) {
                        0 -> mRoadGuideBean.roadName
                        1 -> mRoadGuideBean.hotWord
                        2 -> mRoadGuideBean.pointOtherName
                        3 -> mRoadGuideBean.pointLogoPath
                        4 -> mRoadGuideBean.pointGuidePath
                        6 -> mRoadGuideBean.pointMapName
                        7 -> mRoadGuideBean.voiceContent
                        else -> null
                    }
                }

            }
        }
    }


    private val setNameTipBuilder by lazy { DialogBuildHelper.createDialogSetName(this) }
    private fun showNameDialog(roadSetBean: RoadSetBean, adapterPosition: Int) {
        val text = when (adapterPosition) {
            0 -> mRoadGuideBean.roadName
            2 -> mRoadGuideBean.pointOtherName
            else -> null
        }
        setNameTipBuilder.setTitle(roadSetBean.roadSetTitle)
                .setContent(text)
                .setHintTextTv(null, false)
        setNameTipBuilder.setClickListener(object : DialogBuildHelper.ISetNameClickListener() {
            override fun sure(text: String?, tipTextView: TextView?) {
                if (adapterPosition == 0) {
                    mRoadGuideBean.roadName = text
                } else if (adapterPosition == 2) {
                    mRoadGuideBean.pointOtherName = text
                }
                roadGuideRecyclerView.adapter?.notifyItemChanged(adapterPosition)
            }
        }, true).show()
    }


    private val hotNameDialogView by lazy {
        LayoutInflater.from(this).inflate(R.layout.dialog_set_hot_word, null as ViewGroup?)
    }

    private val hotNameDialog: AlertDialog by lazy {
        val inputFilter = object : InputFilter {
            override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
                for (i in start until end) {
                    if (!isChineseOrEnglish(source[i].toString())) {
                        return ""
                    }
                }
                return source
            }
        }
        val dialogBuilder = AlertDialog.Builder(this, R.style.MyDialogStyle2)
                .setCancelable(false)
                .setView(hotNameDialogView)
        hotNameDialogView.contentView1.filters = arrayOf(inputFilter, InputFilter.LengthFilter(6))
        hotNameDialogView.contentView2.filters = arrayOf(inputFilter, InputFilter.LengthFilter(6))
        hotNameDialogView.contentView3.filters = arrayOf(inputFilter, InputFilter.LengthFilter(6))
        hotNameDialogView.dialog_cancel.setOnClickListener {
            hotNameDialog.dismiss()
        }
        dialogBuilder.create()
    }


    private fun showHotWordDialog(adapterPosition: Int) {
        hotNameDialogView.contentView1.text = null
        hotNameDialogView.contentView2.text = null
        hotNameDialogView.contentView3.text = null
        mRoadGuideBean.hotWord?.let {
            val split = it.split("|")
            split.forEachIndexed { index, s ->
                when (index) {
                    0 -> hotNameDialogView.contentView1.run {
                        setText(s)
                        setSelection(s.length)
                    }
                    1 -> hotNameDialogView.contentView2.run {
                        setText(s)
                        setSelection(s.length)
                    }
                    2 -> hotNameDialogView.contentView3.run {
                        setText(s)
                        setSelection(s.length)
                    }
                }
            }
        }

        hotNameDialogView.dialog_sure.setOnClickListener {
            val text1 = hotNameDialogView.contentView1.text
            val text2 = hotNameDialogView.contentView2.text
            val text3 = hotNameDialogView.contentView3.text
            if (text1.isEmpty() && text2.isEmpty() && text3.isEmpty()) {
                toastTools.showText(getString(R.string.please_input_same_word))
                return@setOnClickListener
            }

            if (text1.length == 1 || text2.length == 1 || text3.length == 1) {
                toastTools.showText(getString(R.string.hot_word_hint))
                return@setOnClickListener
            }
            val stringBuilder = StringBuilder()
            if (text1.isNotEmpty()) {
                stringBuilder.append(text1)
            }
            if (text2.isNotEmpty()) {
                if (stringBuilder.isNotEmpty()) {
                    stringBuilder.append("|")
                }
                stringBuilder.append(text2)
            }
            if (text3.isNotEmpty()) {
                if (stringBuilder.isNotEmpty()) {
                    stringBuilder.append("|")
                }
                stringBuilder.append(text3)
            }
            mRoadGuideBean.hotWord = stringBuilder.toString()
            roadGuideRecyclerView.adapter?.notifyItemChanged(adapterPosition)
            hotNameDialog.dismiss()
        }
        hotNameDialog.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            CHOOSE_PIC_LOGO -> {
                data?.getStringExtra(BaseChoosePicActivity.PIC_PATH).let {
                    mRoadGuideBean.pointLogoPath = it
                    roadGuideRecyclerView.adapter?.notifyItemChanged(3)
                }
            }
            CHOOSE_PIC_GUIDE -> {
                data?.getStringExtra(BaseChoosePicActivity.PIC_PATH).let {
                    mRoadGuideBean.pointGuidePath = it
                    roadGuideRecyclerView.adapter?.notifyItemChanged(4)
                }
            }
            CHOOSE_JOP_POSITION -> {
                data?.let {
                    mRoadGuideBean.pointMapName = it.getStringExtra("jopPosition")
                    mRoadGuideBean.mapID = it.getLongExtra("mapID", -1)
                    roadGuideRecyclerView.adapter?.notifyItemChanged(6)
                }

            }
            CHOOSE_CUSTOM_VOICE -> {
                data?.let {
                    mRoadGuideBean.voiceType = it.getIntExtra(BaseVoiceSetActivity.AUDIO_TYPE_KEY, 1)
                    mRoadGuideBean.voiceContent = it.getStringExtra(BaseVoiceSetActivity.AUDIO_PATH_OR_CONTENT)
                    roadGuideRecyclerView.adapter?.notifyItemChanged(if (mRoadGuideBean.openGuide) 7 else 6)
                }
            }
        }

    }


    private fun upVoice2Head(arrList: ArrayList<AudioEvent>) {
        showBaseLoadDialog()
        val url = IpMsgConst.HTTP_URL + "guideMapAction"
        val hashMap = HashMap<String, Any>()
        hashMap["type"] = "1"
        hashMap["data"] = JSON.toJSONString(arrList)
        arrList.forEach {
            hashMap[it.musicName] = File(PathConst.ROOT_PATH + it.musicPath)
        }
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                toastTools.showText(getString(R.string.up_voice_success))
                upDataType2Service()
            }

            override fun onFailure() {
                dismissBaseDialog()
                toastTools.showText(getString(R.string.service_error_hint))
            }
        })

    }

    private fun upDataType2Service() {
        showBaseLoadDialog()
        val url = IpMsgConst.HTTP_URL_CHEST + "roadGuideAction"
        val hashMap = HashMap<String, Any>()
        hashMap["type"] = "$TYPE_ADD_OR_UPDATE_ROAD"
        hashMap["data"] = JSON.toJSONString(mRoadGuideBean)
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                Log.e(TAG, "upVoice2Head$result")
                dismissBaseDialog()
                mRoadGuideBean.id = result.toInt()
                setResult(Activity.RESULT_OK, Intent().putExtra(RoadGuideActivity.ROAD_GUIDE_INFO, mRoadGuideBean))
                finish()
                toastTools.showText(getString(R.string.upload_complete))
            }

            override fun onFailure() {
                dismissBaseDialog()
                toastTools.showText(getString(R.string.service_error_hint))
            }
        })
    }

    private val setVoice = MapVoiceAndEyes.VoiceAndEyesInfo(RoadGuideActivity.ROAD_GUIDE_VOICE_DIR + "wzxxsz_wlzy_u05_001.mp3", "30")

    companion object {
        const val TAG = "RoadSettingActivity"
        const val CHOOSE_PIC_LOGO = 1001
        const val CHOOSE_PIC_GUIDE = 1002
        const val CHOOSE_JOP_POSITION = 1003
        const val CHOOSE_CUSTOM_VOICE = 1004

        const val TYPE_GET_ALL = 0
        const val TYPE_ADD_BY_MAP = 1
        const val TYPE_ADD_OR_UPDATE_ROAD = 2
        const val TYPE_DELETE_BY_ID = 3
        const val TYPE_RENAME_BY_ID = 4

    }
}